<script setup>
import { useRouter } from 'vue-router';
import { GetUserInfo,uploadAvatar,upUserInfo } from '@/api/user'
import { ref } from "vue"
import { showToast } from 'vant';
import { onMounted, onUnmounted } from 'vue';



let errimg = new URL('../../../assets/img/erricon.png', import.meta.url).href ;

async function uploadUserAvatar(e){
  landingShow.value = true
  let inputDOM = e.target.files[0]
  let formData = new FormData();
  formData.append('file',inputDOM)
  let res = await uploadAvatar(formData,get_token())
  console.log(JSON.stringify(res))
  user_info.value.headIcon = res.data['data']['imgUrl']
  let upres = await upUserInfo(user_info.value,get_token())
  console.log(JSON.stringify(upres))
  landingShow.value = false
  if(upres.data.msg === 'ok'){
    showToast('保存成功');
  }else{
    showToast(`${upres.data.msg}`);
  }

}

let upUserInfoShow = ref(false)

let upTitle = ref('')
let editUserInfo = (title)=>{
  upUserInfoShow.value = true
  upTitle.value = title
}

let editColse = () => {
  console.log('66666')
  user_info.value.nickName   = uRes.nickName
  // upUserInfoShow.value = false

}
async function editUesrInfo(){
  landingShow.value = true
  console.log('ttttt')

  editData.value.nickName = upnickname.value
  let upres = await upUserInfo(user_info.value,get_token())
  // get_user_info()
  console.log(JSON.stringify(upres))
  landingShow.value = false
  if(upres.data.msg === 'ok'){
    showToast('保存成功');
  }else{
    showToast(`${upres.data.msg}`);
  }

}

let uRes = {}
let userfileList = ref([])



let landingShow = ref(false)

const router = useRouter();
let gotoBack = () => {

    router.back()
    // window.location.reload(); // 刷新当前页面
    // showToast('返回成功')

}
let upnickname = ref('')
let editData = ref({
  nickName: '',
  headIcon: '',
  gender: '',
  birthday: ''
})

let user_info = ref({
    nickName: '',
    headIcon: '',
    gender: '',
    birthday: ''
})
async function get_user_info(token) {
    let params = `?k=7636500`
    let res = await GetUserInfo(params,token)
    uRes = res.data.data
    user_info.value   = uRes
    editData.value = uRes
    upnickname.value = uRes.nickName
    console.log(JSON.stringify(user_info.value))
    console.log(JSON.stringify(userfileList.value))
}

const selectedValues = ref([]);

let selectedSexShow = ref(false)

const columns = [
  { text: '男', value: 1 },
  { text: '女', value: 2 },
  { text: '保密', value: 3 },
];

let  sexInfoClick= ()=>{
  selectedSexShow.value = true
  // let uSex = user_info.value.gender
  selectedValues.value =  [user_info.value.gender]

}

async function onConfirmUp (){
  selectedSexShow.value = false;
  landingShow.value = true
  user_info.value.gender =  selectedValues.value[0]
  let upres = await upUserInfo(user_info.value,get_token())
  console.log(JSON.stringify(upres))
  landingShow.value = false
  if(upres.data.msg === 'ok'){
    showToast('保存成功');
  }else{
    showToast(`${upres.data.msg}`);
  }
}


let selectedDateShow = ref(false)
const selectedDateValues = ref([user_info.value.birthday]);
const currentDate = ref(['2016','05','01']);
const columnsType = ['year', 'month' , 'day'];
let minDate = new Date(1900, 1, 1)
let maxDate= new Date(2099, 12, 30)
let  dateClick= ()=>{
  selectedDateShow.value = true;
  let udate = user_info.value.birthday.toString()
  currentDate.value = udate.split("-"); // 使用-作为分隔符
}
function get_token(){
  let token = localStorage.getItem("token")
  if (!!token){
    token=token.replace("\"","").replace("\"","");
  }
  return token
}

async function dateOnConfirm (){
  landingShow.value = true
  selectedDateShow.value = false;
  console.log(currentDate.value)
  user_info.value.birthday = currentDate.value.join('-');
  console.log(user_info.value.birthday); // 输出：12345
  let upres = await upUserInfo(user_info.value,get_token())
  console.log(JSON.stringify(upres))
  landingShow.value = false
  if(upres.data.msg === 'ok'){
    showToast('保存成功');
  }else{
    showToast(`${upres.data.msg}`);
  }

}

const formatter = (type, option) => {
  if (type === 'year') {
    option.text += '年';
  }
  if (type === 'month') {
    option.text += '月';
  }
  return option;
};



onMounted(() => {
  let token = localStorage.getItem("token")
  if (!!token){
    token=token.replace("\"","").replace("\"","");
  }
    get_user_info(token)
})

</script>

<template>
    <div class="my-body">
      <van-overlay :show="landingShow" z-index="100">
        <div class="wrapper" @click.stop>
          <div class="block">
            <van-loading color="#0094ff" text-color="#0094ff" size="24px" vertical>保存中...</van-loading>
          </div>
        </div>
      </van-overlay>

        <van-sticky>
          <div class="top-box"></div>
          <div class="upinfo-header">
            <van-nav-bar class="upinfo-title" title="我的资料"  @click-left="gotoBack">
              <template #left>
                <van-icon name="arrow-left" size="20" color="#6f7070" />
                <van-icon name="left-text" size="20" color="#6f7070" />
              </template>
            </van-nav-bar>
          </div>
        </van-sticky>


        <div  class="cell-card">
<!--            <input class="inputPic" type="file" hidden accept="image/*"  id="input-file">-->


          <input class="inputPic" type="file"  id="input-file" ref="file" style="display: none"  accept="image/*"  @change='uploadUserAvatar'>
          <van-dialog  v-model:show="upUserInfoShow" :title="upTitle" show-cancel-button confirmButtonText="提交" @cancel="editColse" @confirm="editUesrInfo" theme="round-button">

              <van-field
                  autosize
                  show-word-limit
                  v-model="upnickname"
                  maxlength="12"
                  clearable
                  clear-trigger="always"
                  placeholder="请输入用户名"
              />

          </van-dialog>



          <label for="input-file"  >
                <van-cell title="头像" class="avatar-cell" is-link to="">
                    <template #right-icon>
<!--                      <img style="width:40px;height:40px;border-radius: 20px;" :src="user_info.headIcon?user_info.headIcon:errimg"/>-->

                      <van-image width="40" height="40" round    :src="user_info.headIcon?user_info.headIcon:errimg"/>
                        <van-icon name="arrow" size="17" color="#969799" />
                    </template>
                </van-cell>
            </label>

            <van-cell title="昵称" :value="user_info.nickName" @click="editUserInfo('修改昵称')" is-link to="" />
            <van-cell title="性别" :value="user_info.gender == 1 ? '男' :user_info.gender ==2 ?'女':'保密'" @click="sexInfoClick" is-link to="" />
            <van-cell title="出生日期" :value="user_info.birthday == '0000-00-00' ? '未设置'  : user_info.birthday" @click="dateClick" is-link
                to="" />
        </div>
      <van-popup v-model:show="selectedSexShow" round position="bottom">
        <van-picker v-show="selectedSexShow"
                    v-model="selectedValues"
                    title="选择性别"
                    :columns="columns"
                    @cancel="selectedSexShow = false"
                    @confirm="onConfirmUp"
        />
      </van-popup>

      <van-popup v-model:show="selectedDateShow" round position="bottom">
      <van-date-picker
          v-show="selectedDateShow"
          v-model="currentDate"
          title="选择年月"
          :min-date="minDate"
          :max-date="maxDate"
          :formatter="formatter"
          :columns-type="columnsType"
          @cancel="selectedDateShow = false"
          @confirm="dateOnConfirm"
      />
      </van-popup>



    </div>


</template>

<style scoped src="../css/UpdateUserInfo.css"></style>